﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Diagnostics;
using Microsoft.Phone.Controls;

namespace RSSReader
{
  public partial class Mainpage : PhoneApplicationPage
  {
    public class FeedTile
    {
      public Canvas Container;
      public TextBlock Title;
      public TextBlock Count;
      public string Url;
      public string BaseName;

      public FeedTile(int tileNo, string url, string title, int count, int min=0, int range=100)
      {
        Url = url;
        BaseName = title;
        Container = new Canvas();
        Container.Name = title + "_canvas";
        if (title.Equals(App.ALLITEMSNAME))
        {
          Container.Height = 173;
          Container.Width = 356;
        }
        else
        {
          Container.Height = Container.Width = 173;
        }
        Container.Background = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
        Container.Margin = new Thickness(10, 10, 0, 0);
        Title = new TextBlock();
        Title.Name = title + "_title";
        Title.Text = title;
        Title.Loaded += onLoaded;
        Container.Children.Add(Title);
        Canvas.SetLeft(Title, 6);
        Canvas.SetTop(Title, 10);

        Count = new TextBlock();
        Count.Name = title + "_count";
        setTextOfCount(count, min, range);

        Container.Children.Add(Count);
        Canvas.SetLeft(Count, (Container.Width - Count.ActualWidth) * 0.5);
        Canvas.SetTop(Count, (Container.Height - Count.ActualHeight) * 0.5);
      }

      public void setTextOfCount(int count, int min, int range)
      {
        if (count == 0)
        {
          Count.Text = "";
        }
        else
        {
          Count.Text = Convert.ToString(count);
          Count.FontSize = 85.0 * ((count+1)-min) / range;
          if (Count.FontSize > 85.0) Count.FontSize = 85.0;
          else if (Count.FontSize < 20.0) Count.FontSize = 20.0;
          Canvas.SetLeft(Count, (Container.Width - Count.ActualWidth) * 0.5);
          Canvas.SetTop(Count, (Container.Height - Count.ActualHeight) * 0.5);
        }
      }

      private void onLoaded(object sender, RoutedEventArgs e)
      {
        while (Title.ActualWidth + 12 > Container.Width)
        {
          Title.FontSize -= 0.1;
        }
      }
    }
  }
}
